from typing import Tuple, Union

import ujson
from peewee import IntegrityError

from cache.language_cache import LanguageCache
from common.g.g import G_LOGGER
from common.model.language.language import TotalLanguage
from common.utils.resp import RC
from common.v.v import LANGUAGE, DATAORCODE
from schema.req_schema.language_req_schema import AddNewLanguageModel
from service.base import Service


class LanguageService(Service):
    CACHE_CLS = LanguageCache

    async def get_language_list(self) -> Tuple[bool, Union[DATAORCODE, int]]:
        try:
            cache_data = await self.cache.get_language_list(LANGUAGE.TOTAL_LANGUAGE_INFO)
            if cache_data:
                return True, DATAORCODE(data=ujson.loads(cache_data))
        except Exception as e:
            G_LOGGER.exception(f"查找缓存失败:{e}")
        try:
            res = await TotalLanguage.search_instances(self.mgw, condition={}, fields=["id", "name", "code"])
        except Exception as e:
            G_LOGGER.exception(f"查找信息失败:{e}")
            return False, DATAORCODE(data=None, code=RC.DB_ERROR, msg="服务异常,请稍后再试")
        try:
            if res:
                await self.cache.set_total_currency_info_list(LANGUAGE.TOTAL_LANGUAGE_INFO, ujson.dumps(list(res)), ex=30 * 60)
                await self.cache.add_item_to_language_set(LANGUAGE.TOTAL_LANGUAGE_SET, [l.get("code") for l in res])
            else:
                await self.cache.set_total_currency_info_list(LANGUAGE.TOTAL_LANGUAGE_INFO, ujson.dumps([]), px=60)
        except Exception as e:
            G_LOGGER.exception(f"更新缓存失败:{e}")
        return True, DATAORCODE(data=list(res))

    async def add_new_language(self, language_model: AddNewLanguageModel):
        res = await self.exist(TotalLanguage, {"code": language_model.code})
        if res:
            return False, DATAORCODE(data=None, code=RC.LANGUAGE_ALREADY_EXIST, msg="重复添加语言")
        try:
            language_id = await TotalLanguage.add_new_instance(self.mgw, **language_model.dict())
            return True, DATAORCODE(data={"language_id": language_id})
        except IntegrityError as e:
            G_LOGGER.error(f"重复添加语言：{e}")
            return False, DATAORCODE(data=None, code=RC.LANGUAGE_ALREADY_EXIST, msg="重复添加语言")

        except Exception as e:
            G_LOGGER.exception(f"新增语言异常:{e}")
            return False, DATAORCODE(data=None, code=RC.DB_ERROR, msg="服务异常,请稍后重试")

    async def is_language_exist(self, language_code):
        return await self.cache.is_language_exist(LANGUAGE.TOTAL_LANGUAGE_SET, language_code)
